package us.gaaoc.framework.webapp.controllers.tag;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import us.gaaoc.framework.dao.ModelFacade;
import us.gaaoc.framework.model.CaseRecord;
import us.gaaoc.framework.model.Person;
import us.gaaoc.framework.service.TagService;

@Controller
@RequestMapping(value="/tags")
public class TagController {
	
	@Autowired
	ModelFacade mf;
	
	@Autowired
	TagService tagService;
	
	@Transactional
	@RequestMapping(method=RequestMethod.POST,value="/toggle")	
	public ResponseEntity<String> toggleTag(
			HttpSession session,
			@RequestParam("caseRecord") String caseRecordUuid) {
		
		//request
		Person p = (Person) session.getAttribute("person");
		CaseRecord cr = (CaseRecord) mf.getSession().get(CaseRecord.class,caseRecordUuid);		
		
		//logic
		tagService.toggle(cr, p);
					
		//response	    
		boolean isTagged = tagService.isTagged(cr, p);		
		
		HttpHeaders responseHeaders = new HttpHeaders();
	    responseHeaders.setContentType(MediaType.APPLICATION_JSON);
		String json = String.format("{tagged:'%s'}",isTagged);		
		return new ResponseEntity<String>(json, responseHeaders, HttpStatus.OK);		
	}

}
